package com.tdg.qywx.Aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
public class RequestLogAspect {
    private static final Logger _logger = LoggerFactory.getLogger(RequestLogAspect.class);

    // 切入所有Controller的公共方法
    @Pointcut("execution(* com.tdg.qywx.controller..*.*(..))")
    public void controllerPointcut() {}

    @Around("controllerPointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes)
                RequestContextHolder.currentRequestAttributes()).getRequest();

        // 记录请求信息
        _logger.debug("请求URL: {}", request.getRequestURL());
        _logger.debug("HTTP方法: {}", request.getMethod());
        _logger.debug("IP地址: {}", request.getRemoteAddr());
        _logger.debug("请求参数: {}", Arrays.toString(joinPoint.getArgs()));

        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long timeCost = System.currentTimeMillis() - start;

        // 记录响应信息
        _logger.debug("响应结果: {}", result.toString());
        _logger.debug("执行耗时: {} ms", timeCost);

        return result;
    }
}